package cn.wygandwdn.core.registry.impl;

import cn.wygandwdn.common.config.RpcServiceConfig;
import cn.wygandwdn.common.factory.SingletonFactory;
import cn.wygandwdn.common.utils.IpAddressUtil;
import cn.wygandwdn.core.config.Config;
import cn.wygandwdn.core.registry.PublishService;
import cn.wygandwdn.core.registry.ServiceProvider;
import cn.wygandwdn.core.registry.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/30 14:53
 */

public class PublishServiceImpl implements PublishService {
    private static final Logger log = LoggerFactory.getLogger(PublishServiceImpl.class);

    private final ServiceRegistry registry;
    private final ServiceProvider provider;
    private String host;
    private int port;

    public PublishServiceImpl() {
        this.registry = Config.getRegistry();
        this.provider = SingletonFactory.getInstance(ServiceProviderImpl.class);
        try {
            this.host = IpAddressUtil.getHost();
        } catch (UnknownHostException e) {
            log.error("get host error: {}", e);
        }
        this.port = Config.getServerPort();
    }

    @Override
    public void publishService(RpcServiceConfig config) {
        Object service = config.getService();
        Class<?>[] interfaces = service.getClass().getInterfaces();
        for (Class<?> anInterface : interfaces) {
            String serviceName = anInterface.getCanonicalName() + "$" + config.getGroup() + "$" + config.getVersion();
            provider.addService(service, serviceName);
            registry.registry(serviceName, host, port);
        }
    }
}
